package pswvclass.pswvandroid2.com.kwords;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.need.Skyset;
import pswvclass.pswvandroid2.com.user.UserPerfect;
import pswvclass.pswvandroid2.com.util.DBHelper;
import pswvclass.pswvandroid2.com.util.HandleBackInterface;
import pswvclass.pswvandroid2.com.util.HandleBackUtil;
import pswvclass.pswvandroid2.com.util.HttpUtils;
import pswvclass.pswvandroid2.com.util.SpinnerData;
import pswvclass.pswvandroid2.com.util.StreamTool;

/**
 * Created by Administrator on 2018/11/1.
 */
public class KwordAdd extends Fragment implements View.OnClickListener {
    private String tag = "KwordAdd";
    private TextView kwords;
    private TextView content;
    private Button add_kword;
    private Button share_kword;
    private Spinner pswv_category;
    private List<SpinnerData> list;
    private static int a = 0;//表示是否第一次提交
    private static int b = 0;//表示是否第一次提交
    private static int kwordId = 0;
    private static int shareKWordId = 0;
    protected static final int SUCCESS_ADD = 8;
    protected static final int SPINNER_SUCCESS = 7;
    protected static final int INCOMPLET_DATA = 6;
    protected static final int SUCCESS_SHARE1 = 5;
    protected static final int ADD_SHARE_ERROR = 4;
    protected static final int ADD_ERROR = 3;
    protected static final int SUCCESS_SHARE = 2;
    protected static final int ERROR = 1;
    protected static final int SUCCESS = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.pswv_kword_add, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        a = 0;
        kwordId = 0;
        b = 0;
        shareKWordId = 0;
        pswv_category = (Spinner) getView().findViewById(R.id.pswv_category);
        kwords = (EditText) getView().findViewById(R.id.pswv_kword);
        content = (EditText) getView().findViewById(R.id.pswv_context);
        add_kword = (Button) getView().findViewById(R.id.add_kword);
        add_kword.setOnClickListener(this);
        share_kword = (Button) getView().findViewById(R.id.share_kword);
        share_kword.setOnClickListener(this);
        if (bundle != null) {
            String kwords3 = bundle.getString("kwords");
            String content3 = bundle.getString("content");
            kwords.setText(kwords3);
            content.setText(content3);
        }
        new Thread() {
            public void run() {
                try {
                    HttpUtils hu = new HttpUtils();
                    String data2;
                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/categoryAcion/listAll";
                    data2 = hu.submitPostData(src, "utf-8");
                    JSONObject jsonObj = new JSONObject(data2);
                    int result = Integer.parseInt(jsonObj.getString("code"));
                    JSONArray array = jsonObj.getJSONArray("response");
                    if (result == 0) {
                        list=new ArrayList<SpinnerData>();
                        for (int i = 0; i <array.length();i++ ) {
                            JSONObject temp = (JSONObject) array.get(i);
                            SpinnerData c = new SpinnerData(temp.getInt("id"), temp.getString("name"));
                            Log.v(tag, temp.getInt("id") + "");
                            list.add(c);
                        }
                        Message msg = Message.obtain();
                        msg.what = SPINNER_SUCCESS;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = ERROR;
                    mHandler.sendMessage(msg);
                    Log.v(tag, e + "");
                }
            }
        }.start();

    }

    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS_ADD:{
                    final String kwords1 = kwords.getText().toString().trim();
                    final String content1 = content.getText().toString().trim();
                    final int categoryId = ((SpinnerData) pswv_category.getSelectedItem()).getValue();
                    if (TextUtils.isEmpty(kwords1) || TextUtils.isEmpty(content1)) {
                        Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    DBHelper db = new DBHelper(getContext());
                    SQLiteDatabase sd = db.getWritableDatabase();
                    int userId = 0;
                    Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                    while (cursor.moveToNext()) {
                        userId = cursor.getInt(0);
                        Log.v(tag, userId + "");
                    }
                    cursor.close();
                    final int finalUserId = userId;
                    if (a == 0) {
                        new Thread() {
                            public void run() {
                                try {
                                    HttpUtils hu = new HttpUtils();
                                    String data2;
                                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/keysAcion/androidadd";
                                    final Map<String, String> map1 = new HashMap<String, String>();
                                    map1.put("userId", finalUserId + "");
                                    map1.put("kwords", kwords1);
                                    map1.put("content", content1);
                                    data2 = hu.submitPostData(src, map1, "utf-8");
                                    JSONObject jsonObj = new JSONObject(data2);
                                    JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                                    int result = Integer.parseInt(jsonObj.getString("code"));
                                    if (result == 0) {
                                        a = 1;
                                        kwordId = jsonObj1.getInt("kWordId");
                                        Message msg = Message.obtain();
                                        msg.what = SUCCESS;
                                        mHandler.sendMessage(msg);
                                    } else if (result == 19) {
                                        Message msg = Message.obtain();
                                        msg.what = ADD_ERROR;
                                        mHandler.sendMessage(msg);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Message msg = Message.obtain();
                                    msg.what = ERROR;
                                    mHandler.sendMessage(msg);
                                    Log.v(tag, e + "");
                                }
                            }
                        }.start();
                    } else {
                        new Thread() {
                            public void run() {
                                try {
                                    HttpUtils hu = new HttpUtils();
                                    String data2;
                                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/keysAcion/edit";
                                    final Map<String, String> map1 = new HashMap<String, String>();
                                    map1.put("id", kwordId + "");
                                    map1.put("kwords", kwords1);
                                    map1.put("content", content1);
                                    data2 = hu.submitPostData(src, map1, "utf-8");
                                    JSONObject jsonObj = new JSONObject(data2);
                                    int result = Integer.parseInt(jsonObj.getString("code"));
                                    if (result == 0) {
                                        Message msg = Message.obtain();
                                        msg.what = SUCCESS;
                                        mHandler.sendMessage(msg);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Message msg = Message.obtain();
                                    msg.what = ERROR;
                                    mHandler.sendMessage(msg);
                                    Log.v(tag, e + "");
                                }
                            }
                        }.start();
                    }
                }
                break;
                case SPINNER_SUCCESS: {
                    ArrayAdapter<SpinnerData> adapter = new ArrayAdapter<SpinnerData>(getContext(),android.R.layout.simple_spinner_item, list);
                    //设置下拉列表的风格
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                    //将adapter 添加到spinner中
                    pswv_category.setAdapter(adapter);

                    //添加事件Spinner事件监听
                   // pswv_category.setOnItemSelectedListener(new SpinnerSelectedListener());

                    //设置默认值
                    pswv_category.setVisibility(View.VISIBLE);
                    break;
                }
                case INCOMPLET_DATA: {
                    final String kwords1 = kwords.getText().toString().trim();
                    final String content1 = content.getText().toString().trim();
                    UserPerfect up = new UserPerfect();
                    Bundle bundle = new Bundle();
                    bundle.putString("kwords", kwords1);
                    bundle.putString("content", content1);
                    bundle.putInt("status", 0);
                    up.setArguments(bundle);
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, up).commit();
                    Toast.makeText(getContext(), "请完善资料", Toast.LENGTH_SHORT).show();
                    break;
                }
                case ADD_ERROR: {
                    Toast.makeText(getContext(), "内容重复添加！！", Toast.LENGTH_SHORT).show();
                    break;
                }
                case ADD_SHARE_ERROR: {
                    Toast.makeText(getContext(), "分享内容重复添加！！", Toast.LENGTH_SHORT).show();
                    break;
                }
                case SUCCESS: {
                    Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
                    break;
                }
                case SUCCESS_SHARE: {
                    final String kwords1 = kwords.getText().toString().trim();
                    final String content1 = content.getText().toString().trim();
                    if (TextUtils.isEmpty(kwords1) || TextUtils.isEmpty(content1)) {
                        Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    DBHelper db = new DBHelper(getContext());
                    SQLiteDatabase sd = db.getWritableDatabase();
                    int userId = 0;
                    Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                    while (cursor.moveToNext()) {
                        userId = cursor.getInt(0);
                    }
                    cursor.close();
                    final int finalUserId = userId;
                    if (b == 0) {
                        new Thread() {
                            public void run() {
                                try {
                                    HttpUtils hu = new HttpUtils();
                                    String data2;
                                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/shareKWordAction/androidadd";
                                    final Map<String, String> map1 = new HashMap<String, String>();

                                    map1.put("userId", finalUserId + "");
                                    map1.put("kwords", kwords1);
                                    map1.put("content", content1);
                                    data2 = hu.submitPostData(src, map1, "utf-8");
                                    JSONObject jsonObj = new JSONObject(data2);
                                    int result = Integer.parseInt(jsonObj.getString("code"));
                                    JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                                    if (result == 0) {
                                        b = 1;
                                        shareKWordId = jsonObj1.getInt("shareKWordId");
                                        Message msg = Message.obtain();
                                        msg.what = SUCCESS_SHARE1;
                                        mHandler.sendMessage(msg);
                                    } else if (result == 19) {
                                        Message msg = Message.obtain();
                                        msg.what = ADD_SHARE_ERROR;
                                        mHandler.sendMessage(msg);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Message msg = Message.obtain();
                                    msg.what = ERROR;
                                    mHandler.sendMessage(msg);
                                    Log.v(tag, e + "");
                                }
                            }
                        }.start();
                    } else {
                        new Thread() {
                            public void run() {
                                try {
                                    HttpUtils hu = new HttpUtils();
                                    String data2;
                                    final String src = getResources().getString(R.string.src_mysql) + "pswv/api/shareKWordAction/edit";
                                    final Map<String, String> map1 = new HashMap<String, String>();
                                    map1.put("id", shareKWordId + "");
                                    map1.put("kwords", kwords1);
                                    map1.put("content", content1);
                                    data2 = hu.submitPostData(src, map1, "utf-8");
                                    JSONObject jsonObj = new JSONObject(data2);
                                    int result = Integer.parseInt(jsonObj.getString("code"));
                                    if (result == 0) {
                                        Message msg = Message.obtain();
                                        msg.what = SUCCESS_SHARE1;
                                        mHandler.sendMessage(msg);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Message msg = Message.obtain();
                                    msg.what = ERROR;
                                    mHandler.sendMessage(msg);
                                    Log.v(tag, e + "");
                                }
                            }
                        }.start();
                    }
                    break;
                }
                case SUCCESS_SHARE1: {
                    Toast.makeText(getContext(), "等待审核", Toast.LENGTH_SHORT).show();
                    break;
                }
                case ERROR: {
                    Toast.makeText(getContext(), "连接错误 ....", Toast.LENGTH_SHORT).show();
                    break;
                }
                default: {
                    break;
                }
            }
        }

        ;
    };

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.add_kword: {
                final String kwords1 = kwords.getText().toString().trim();
                final String content1 = content.getText().toString().trim();

                if (TextUtils.isEmpty(kwords1) || TextUtils.isEmpty(content1)) {
                    Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;

                new Thread() {
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/userAction/checkUserWhetherPerfect";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            map1.put("id", finalUserId + "");
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.what = SUCCESS_ADD;
                                mHandler.sendMessage(msg);
                            } else if (result == 22) {
                                Message msg = Message.obtain();
                                msg.what = INCOMPLET_DATA;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                            Log.v(tag, e + "");
                        }
                    }
                }.start();
            }
            break;
            case R.id.share_kword: {
                final String kwords1 = kwords.getText().toString().trim();
                final String content1 = content.getText().toString().trim();

                if (TextUtils.isEmpty(kwords1) || TextUtils.isEmpty(content1)) {
                    Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;

                new Thread() {
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/userAction/checkUserWhetherPerfect";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            map1.put("id", finalUserId + "");
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.what = SUCCESS_SHARE;
                                mHandler.sendMessage(msg);
                            } else if (result == 22) {
                                Message msg = Message.obtain();
                                msg.what = INCOMPLET_DATA;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                            Log.v(tag, e + "");
                        }
                    }
                }.start();
            }
            break;
            default:
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, new KwordList()).commit();
                    return true;
                }
                return false;
            }
        });
    }

}
